package com.ambimmort.shj.service.user;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.user.manage.MD5Tool;
import cn.net.greenet.user.manage.Util;
import cn.net.greenet.user.operation.QueryUserOperation;
import cn.net.greenet.user.operation.UserLoginAction;
import cn.net.greenet.user.operation.UserLoginOutAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

/**
 * Created by Administrator on 2015/7/31.
 */
@Service
public class UserService {
//    @Autowired
//    private SessionFactory hibernateSessionFactory;
    ResultSet rs =null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }
    /**
     *
     * @param json
     * @throws Throwable
     */
    public String createDomain(String json)  {
        try {
            init();
            JSONObject jo = JSONObject.fromObject(json);
//            hibernateSessionFactory.openSession();
//             baseDao = new BaseDao();
            int row = baseDao.executeUpdate("insert into user(`name`,`pswd`,`email`,`desc`,`isOn`) values(?,?,?,?,?)", new Object[]{jo.get("username"), MD5Tool.GetMD5Code(jo.get("password").toString()), jo.get("email"), jo.get("describe"), 0});
            if (row == 1) {
                   return "{\"result\":\"true\"}";
            } else {
                return "{\"result\":\"false\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"result\":\"false\"}";
        } finally {
//            out.close();
            close();
        }
    }

    /**
     *
     * @param user
     * @throws Throwable
     */
    public String deleteDomain(String user) {
        try {
            init();
//             baseDao = new BaseDao();
            int row = baseDao.executeUpdate("delete from user where `name` = ?", new Object[]{user});
            if (row == 1) {
                return "{\"result\":\"true\"}";
            } else {
                return "{\"result\":\"false\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"result\":\"false\"}";
        } finally {
//            out.close();
            close();
        }
    }

    /**
     *
     * @param json
     * @throws Throwable
     */
    public String editDomain(String json) {
        try {

            JSONObject jo = JSONObject.fromObject(json);
//            baseDao = new BaseDao();
            init();
            int row = baseDao.executeUpdate("update user set `pswd` = ?, `email` = ? ,`desc` = ? where `name` = ?", new Object[]{"0".equals(jo.get("type").toString()) ? jo.get("password").toString() : MD5Tool.GetMD5Code(jo.get("password").toString()), jo.get("email"), jo.get("describe"), jo.get("username")});
            if (row == 1) {
                return "{\"result\":\"true\"}";
            } else {
                return "{\"result\":\"false\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"result\":\"false\"}";
        } finally {
//            out.close();
            close();
        }

    }

    /**
     *
     * @return
     * @throws Throwable
     */
    public String listDomain()  {
        JSONArray joarr = new JSONArray();
//         baseDao = new BaseDao();
        init();
        try {
            rs = baseDao.executeSQL("select * from user", new Object[]{});
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (rs.next()) {
                JSONObject jo = new JSONObject();
                jo.put("name", rs.getString("name"));
                jo.put("last_ip", rs.getString("last_ip") == null ? "未登录" : rs.getString("last_ip"));
                jo.put("lats_in", rs.getString("last_in") == null ? "未登录" : df.format(Long.parseLong(rs.getString("last_in"))));
                jo.put("last_out", rs.getString("last_out") == null ? "未退出" : df.format(Long.parseLong(rs.getString("last_out"))));
                jo.put("email", rs.getString("email"));
                jo.put("isOn", rs.getInt("isOn"));
                jo.put("desc", rs.getString("desc"));
                jo.put("password", rs.getString("pswd"));
                joarr.add(jo);
            }
            return joarr.toString();
        } catch (SQLException ex) {
            return joarr.toString();
//            Logger.getLogger(List.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
//            out.close();
            close();
        }
    }

    /**
     *
     * @param request
     * @param username
     * @throws Throwable
     */
    public String login_outDomain(HttpServletRequest request,String username) {
        try {
//             baseDao = new BaseDao();
            init();
            int row = baseDao.executeUpdate("update user set last_out = ?, isOn = ? where name = ?", new Object[]{System.currentTimeMillis(), 0, username});
            if (row == 1) {
                UserLoginOutAction.insertDB(username);  //生成用户的登出日志
                HttpSession session=request.getSession();
                session.invalidate();
                return "{\"result\":\"true\"}";
//                out.println("{\"result\":\"true\"}");
            } else {
//                out.println("{\"result\":\"false\"}");
                return "{\"result\":\"false\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
            return "{\"result\":\"false\"}";
        } finally {
//            out.close();
            close();
        }
    }

    /**
     *
     * @param json
     * @throws Throwable
     */
    public String loginDomain( HttpServletRequest request,String json)  {
        try {
            JSONObject jo = JSONObject.fromObject(json);
//             baseDao = new BaseDao();
            init();
             rs = baseDao.executeSQL("select pswd ,isOn from user where `name` = ?", new Object[]{jo.get("username")});
            if (rs.next()) {
                if (MD5Tool.GetMD5Code(jo.get("password").toString()).equals(rs.getString("pswd"))) {
//                    if (rs.getInt("isOn") == 1) {
//                        out.println("{\"result\":\"2\"}");   //用户只能使用一个用户名
//                    } else {
                    int row = baseDao.executeUpdate("update user set last_ip = ? ,last_in = ? ,isOn = ? where name = ?", new Object[]{Util.getIpAddr(request), System.currentTimeMillis(), 1, jo.get("username")});
                    if (row == 1) {
                        UserLoginAction.insertDB(jo.get("username").toString(), Util.getIpAddr(request));  //生成用户的登录日志
                        HttpSession session = request.getSession(true);  //create session
                        session.setMaxInactiveInterval(1200*2);  //longtime 10*2 min
                        session.setAttribute("name", jo.get("username"));
                        return  "{\"result\":\"5\"}";
                    } else {
                        return "{\"result\":\"3\"}";
                    }
//                    }
                } else {
                    return "{\"result\":\"1\"}";
                }
            } else {
                return "{\"result\":\"4\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  "{\"result\":\"3\"}";
        } finally {
//            out.close();
            close();
        }

    }

    /**
     *
     * @param username
     * @param starttime
     * @param endtime
     * @param iDisplayStart
     * @param iDisplayLength
     * @return
     */
    public String queryUserOperationServletDomain(String username,String starttime,String endtime,String iDisplayStart,String iDisplayLength) {

//        JSONObject jo = JSONObject.fromObject(json);
//        String endtime = jo.getString("endTime");
//        String iDisplayStart = request.getParameter("iDisplayStart"); //查询的起始条数
//        String iDisplayLength = request.getParameter("iDisplayLength");  //每页显示的条数
            return QueryUserOperation.queryUserOperation(username, starttime, endtime, iDisplayStart, iDisplayLength);
    }
}
